home *** CD-ROM | disk | FTP | other *** search
/ Collection of Tools & Utilities / Collection of Tools and Utilities.iso / system / idt.zip / STOL.C < prev    next >
Text File  |  1988-06-11  |  2KB  |  76 lines

  1. /* STOL.C    More powerful version of atol.
  2. **
  3. **    Copyright (C) 1985 by Allen  Holub.  All rights reserved.
  4. **    This program may be copied for personal, non-profit use only.
  5. */
  6.  
  7. #define islower(c)    ( 'a' <= (c) && (c) <= 'z' )
  8. #define toupper(c)    ( islower(c) ? (c) - ('a' - 'A') : (c) )
  9.  
  10. long    stol( char ** );
  11.  
  12. long    stol( instr )
  13. register char    **instr;
  14. {
  15.     /*    Convert string to long. If string starts with 0x it is
  16.      *    interpreted as a hex number, else if it starts with a 0 it
  17.      *    is octal, else it is decimal. Conversion stops on encountering
  18.      *    the first character which is not a digit in the indicated
  19.      *    radix. *instr is updated to point past the end of the number.
  20.      */
  21.  
  22.     register long    num  = 0;
  23.     register char    *str;
  24.     int        sign = 1;
  25.  
  26.     str = *instr;
  27.  
  28.     while( (*str == ' ')  || (*str == '\t') || (*str == '\n') )
  29.         ++str ;
  30.  
  31.     if( *str == '-' )
  32.         {
  33.         sign = -1;
  34.         ++str;
  35.         }
  36.  
  37.     if ( *str == '0' )
  38.         {
  39.         ++str;
  40.         if ( (*str == 'x') || (*str == 'X') )
  41.             {
  42.             ++str;
  43.             while(    ('0'<= *str && *str <= '9') ||
  44.                 ('a'<= *str && *str <= 'f') ||
  45.                 ('A'<= *str && *str <= 'F')  )
  46.                 {
  47.                 num <<= 4;
  48.                 num += ('0'<= *str && *str <= '9') ?
  49.                     *str - '0'            :
  50.                     toupper(*str) - 'A' + 10   ;
  51.                 ++str;
  52.                 }
  53.             }
  54.         else
  55.             {
  56.             while( '0' <= *str  &&  *str <= '7' )
  57.                 {
  58.                 num <<= 3;
  59.                 num += *str++ - '0' ;
  60.                 }
  61.             }
  62.         }
  63.     else
  64.         {
  65.         while( '0' <= *str  &&  *str <= '9' )
  66.             {
  67.             num *= 10;
  68.             num += *str++ - '0' ;
  69.             }
  70.         }
  71.  
  72.     *instr = str;
  73.     return ( num * sign );
  74. }
  75.  
  76.